var App = App||{};
App.Week = {};
App.Week.init = function(){
	var self = this;
	this.showWeekends = false;
	
	if (localStorage && localStorage.showWeekends == 'true'){
		this.showWeekends = true;
		$('.mainmenu .icon-weekends').addClass('icon-weekends-on');
	}
	
	this.dayTemplate = $("#dayTemplate").template();
	this.dayEditorTemplate = $("#dayEditorTemplate").template();
	
	this.container = $('#wrapper')
		// handle save/cancel buttons
		.delegate('.day .day-header .buttons .button', 'click', function(){ self.editBtnHandler.call(self, $(this)); })
		
		// handle copy/paste buttons
		.delegate('.day .actions .icon', 'click', function(){ self.rowActionHandler.call(self, $(this)); })
		
		// start editor on dblclick
		.delegate('.day .day-content', 'dblclick', function(){ self.startEdit.call(self, $(this).closest('.day'));	})
		
		// remove project from row
		.delegate('.day .project .remove-project', 'click', function(){ self.removeProject.call(self, $(this).closest('.project')); })
		
		// select text on focus
		.delegate('.day .editable-clone textarea', 'focus', function(){ var self=this; this.select(); setTimeout(function(){self.select();},100); return false; });
	
	$('.mainmenu .icon-weekends').bind('click', function(){ self.toggleWeekends.call(self, $(this)); });	
};


App.Week.toggleWeekends = function(icon){
	var cls = 'icon-weekends-on';
	if (icon.hasClass(cls)) {
		if (localStorage) localStorage.showWeekends = false;
		this.showWeekends = false;
		this.reload();
		icon.removeClass(cls);
	}
	else {
		if (localStorage) localStorage.showWeekends = true;
		this.showWeekends = true;
		this.reload();
		icon.addClass(cls);
	};
};



/*** WEEK ACTIONS **************************************************************************************************************/
App.Week.reload = function(){ this.load(location.hash.substr(1),true); };
App.Week.load = function(date,force){
	var daystr = 'day_'+date, daybox = $('#'+daystr);
	if (daybox.length && !force) daybox.addClass('active');
	else {
		$.ajax({ url: "week", context: this, data: { date: date, showWeekends: this.showWeekends } })
		.success(function(data){
			if (!data || data.result == 'error' || data.result == 'auth'){ App.Error(data); return; }
			this.populate(date, data);
		});
	}
};

App.Week.populate = function(date, data){
	var wrapperW = this.container.width(), panel = this.container.find('.week'), 
		newPanel = $('<div id="week_'+date+'" data-date="'+date+'" class="week"/>').append($.tmpl(this.dayTemplate, data));

	if (panel.length) panelW = panel.width();
	else panelW = wrapperW - (panel.length?panel.outerWidth(true)-panel.width():40); 	// wrapper - margins
		
	newPanel.prependTo(this.container);
	panel.css({ position: 'absolute', zIndex: 100, left: 0, top: 0, width: panelW }).animate({ opacity: 0 }, 'fast', 'linear', function(){ panel.remove(); });
		
	var toDay = $('#day_'+(new Date().toStr()));
	if (toDay && toDay.length) toDay.addClass('today').find('.day-caption')[0].innerHTML += ' - today';
	
	this.initEvents();
};


/**
 * Init event listeners on the rendered weeks
 */
App.Week.initEvents = function(){
	$('#wrapper .day-header').droppable('destroy').droppable({ accept: ".project", activeClass: "drop-ready", hoverClass: "drop-hover",
		over: function(ev, ui) { $(ev.target).nextAll('.day-content').addClass('drop-hover'); },
		out:  function(ev, ui) { $(ev.target).nextAll('.day-content').removeClass('drop-hover'); },
		drop: $.proxy(this.projectDrop, this)
	});
	$('#wrapper .day .row').droppable('destroy').droppable({ accept: ".project", activeClass: "drop-ready", hoverClass: "drop-hover", drop: $.proxy(this.projectDrop, this) });
};
/*** WEEK ACTIONS **************************************************************************************************************/







/*** DAY ACTIONS ***************************************************************************************************************/
App.Week.saveDay = function(day){
	var rows = day.find('.editable-clone .row'), rowsL = rows.length, i = 0, data = { date: day.data('date'), rows: [] };
	
    day.find('.project_0').html('').removeClass('empty');
    
	for (; i<rowsL; i++){
		var pr = $(rows[i]).find('.project'),
			name = pr.text(),
			desc = $(rows[i]).find('.description textarea').val();
		if (name == 'drop project here') name = '';		
		data.rows[i] = { projectId: pr.data('projectId'), projectName: name, description: desc };
	}
	
	$.extend(true, day.tmplItem().data, data);
	
	$.ajax({ url: "saveDay", context: this, data: data })
	.success(function(data){
		if (!data || data.result == 'error' || data.result == 'auth') return App.Error(data); 
		msgbox('Day has been saved!');
	});
};
/*** DAY ACTIONS ***************************************************************************************************************/










/*** PROJECT ACTIONS *********************************************************************************************************************************************/
/**
 * Project is dropped on a day
 */
App.Week.projectDrop = function(ev, ui){
	this.container.find('.day .drop-hover').removeClass('drop-hover');
	this.container.find('.day .drop-ready').removeClass('drop-ready');
	var project = ui.draggable, 
		projectId = project.data('projectId'), 
		projectName = project[0].childNodes[1].textContent, 
		target = $(ev.target), $target, day, dayId, replaceIndex = null;
	
	if (target.is('.row')) $target = target.find('.project');
	else $target = target.next('.day-content').find('.row .project');

	day = $target.closest('.day');
	dayId = day.attr('id');
	
	if ($target.closest('.content-readonly').length){															// dropped on the readonly
		if ($target.length>1) replaceIndex = -1;
		else replaceIndex = $target.parent('.row').index();														// dropped on row - replace corresponding			
	}
	
	this.startEdit(day);
	
	if(replaceIndex != null){																					// dropped on readonly - update target ref.
		day = $('#'+dayId);
		if (replaceIndex === -1) $target = day.find('.row .project');
		else $target = day.find('.row').eq(replaceIndex).find('.project');
	}
	
	$target
		.html('<div class="remove-project"></div>'+projectName)
		.data('projectId', projectId)
		.css('background','#95BDD4')
		.removeClass('empty project_0')
		.effect('pulsate', {times:1}, 400, function(){ $(this).css('background',''); });
};

App.Week.removeProject = function(el){ el.fadeOut('fast', function(){ $(this).data('projectId','0').html('drop project here').addClass('empty project_0').fadeIn(); }); };
/*** PROJECT ACTIONS *********************************************************************************************************************************************/








/*** EDIT ACTIONS ************************************************************************************************************************************************/
App.Week.editBtnHandler = function(btn){
	var action = btn.data('action'), day = btn.closest('.day'); 
	if (action == 'save') this.saveEdit(day);
	else this.cancelEdit(day);
};

App.Week.startEdit = function(day){
	if (day.find('.editable-clone').length) return;			// already in edit

    var tplItem = day.tmplItem();							// Get template item associated with DIV
    tplItem.tmpl = this.dayEditorTemplate;					// Change template to compiled template
    tplItem.update();										// Re-render template
    day = $(tplItem.nodes);
    
    day.find('.project_0,.project_').html('drop project here').addClass('empty');
    
    day
		.find('.editable-clone textarea')
		.unbind('keyup', $.proxy(this.onKeyUp, this)).bind('keyup', $.proxy(this.onKeyUp, this))
		.autoResize().first()[0].select();					// autoresize textareas

	var header = day.find('.day-header'), buttons = header.find('.buttons');
	header.css('overflow','hidden');
	buttons.show().css({ top: 30 }).animate({ top: 2 }, 'normal', 'swing', function(){ header.css('overflow',''); });

	this.initEvents();
};


/**
 * Saving a day
 */
App.Week.saveEdit = function(day){ this.saveDay(day); this.cancelEdit(day); };

/**
 * Saving a day has been canceled
 */
App.Week.cancelEdit = function(day){
    var tplItem = day.tmplItem();							// Get template item associated with DIV
    tplItem.tmpl = this.dayTemplate;						// Change template to compiled template
    tplItem.update();										// Re-render template
    day = $(tplItem.nodes);
	
	var header = day.find('.day-header'), buttons = header.find('.buttons');
	header.css('overflow','hidden');
	buttons.show().css({ top: 2 }).animate({ top: 30 }, 'normal', 'swing', function(){ buttons.hide(); header.css('overflow',''); });
	
	this.initEvents();
};

App.Week.onKeyUp = function(e){
	var day = $(e.target).closest('.day'), key = e.keyCode, ENTER = 13, ESC = 27, isCtrl = e.ctrlKey;
	if (key == ESC) this.cancelEdit(day);
	else if (key == ENTER && isCtrl) this.saveEdit(day);
};

App.Week.clearRows = function(rows){
	rows.each(function(){
		var row = $(this);
		row.find('.project').data('projectId','0').html('drop project here').addClass('empty project_0');
		row.find('.description textarea').val('');
	});
};
/*** EDIT ACTIONS ************************************************************************************************************************************************/





/*** COPY & PASTE ACTIONS ****************************************************************************************************************************************/
App.Week.rowActionHandler = function(btn){
	var action = btn.data('action'), row = btn.closest('.row'), day = btn.closest('.day'), dayId = day.attr('id');
	
	if (row.length){											// row action
		if (action == 'copy') App.Clipboard.copy(row);
		else if (action == 'paste') {
			this.startEdit(day);
			day = $('#'+dayId);
			row = day.find('.editable-clone .row').eq(row.index());
			App.Clipboard.paste(row);
		}
		else if (action == 'clear') {
			this.startEdit(day);
			day = $('#'+dayId);
			row = day.find('.editable-clone .row').eq(row.index());
			this.clearRows(row);			
		}
		row.effect('highlight', { color: '#95BDD4' }); 
	}
	
	else {														// day action
		if (action == 'copy') {
			App.Clipboard.copy(day);
			day.find('.content-readonly').effect('highlight', { color: '#95BDD4' }); 
		}
		else if (action == 'paste'){
			this.startEdit(day);
			day = $('#'+dayId);
			App.Clipboard.paste(day); 
			day.find('.editable-clone').effect('highlight', { color: '#95BDD4' }); 
		}
		else if (action == 'clear'){
			this.startEdit(day);
			day = $('#'+dayId);
			var rows = day.find('.editable-clone .row'); 
			this.clearRows(rows);
			day.find('.editable-clone').effect('highlight', { color: '#95BDD4' }); 
		}
	}
};
/*** COPY & PASTE ACTIONS ****************************************************************************************************************************************/
